﻿using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using FullDuplexTest.Contracts;
using N3P.WCF.Proxyless.FullDuplex.Silverlight;

namespace FullDuplexTest.Silverlight
{
    public partial class MainPage
    {
        private readonly WcfClient<IChat, ChatResponse> _chatProxy;

        public MainPage()
        {
            InitializeComponent();

            var machineIdentifier = Guid.NewGuid();

            var response = new ChatResponse(this);
            _chatProxy = new WcfClient<IChat, ChatResponse>(response);
            _chatProxy.Call(x => x.Connect(machineIdentifier));
            response.PingTimedOut += () =>
                                         {
                                             Dispatcher.BeginInvoke(() => ChatHistory.Background = new SolidColorBrush(Colors.Red));
                                             _chatProxy.Reset();
                                             _chatProxy.Call(x => x.Connect(machineIdentifier));
                                         };
        }

        private void ButtonClick(object sender, RoutedEventArgs e)
        {
            _chatProxy.Call(x => x.Send(new ChatMessage {Message = Message.Text, UserName = Username.Text}));
            Message.Text = "";
        }

        private void MessageKeyUp(object sender, KeyEventArgs e)
        {
            if(e.Key == Key.Enter && (Keyboard.Modifiers & ModifierKeys.Shift) == 0)
            {
                ButtonClick(null, null);
            }
            else if (e.Key == Key.Enter && (Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift)
            {
                var selStart = Message.SelectionStart;
                var selLen = Message.SelectionLength;
                var msg = Message.Text;

                if(selLen > 0)
                {
                    Message.Text = msg.Substring(0, selStart) + "\n" + msg.Substring(selStart + selLen);
                    Message.SelectionStart = selStart + 1;
                    return;
                }

                Message.Text += "\n";
                Message.SelectionStart = selStart + 1;
            }
        }
    }
}
